<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form ref="formRef" :model="searchValue">
        <el-row>
          <el-col :span="6" class="pr-5">
            <el-form-item label="标准名称：" prop="dataStandardName">
              <ns-input
                v-model="searchValue.dataStandardName"
                clearable
                placeholder="请输入标准名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pr-5">
            <el-form-item label="标准类型：" prop="type">
              <el-select v-model="searchValue.type" clearable placeholder="请选择标准类型">
                <el-option label="非机构化数据" value="0" />
                <el-option label="结构化数据" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pr-5">
            <el-form-item label="父标准名称：" prop="parentName">
              <ns-input v-model="searchValue.parentName" clearable placeholder="请输入标准名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pr-5">
            <el-form-item label="备注：" prop="remark">
              <ns-input v-model="searchValue.remark" clearable placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pr-5">
            <el-form-item label="状态：" prop="status">
              <el-select v-model="searchValue.status" clearable placeholder="请选择状态">
                <el-option label="开启" value="1" />
                <el-option label="关闭" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pr-5">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="searchValue.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-240px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="searchReset" plain v-hasPermi="['system:data-standards:search']"
              >重置</el-button
            >
            <el-button
              @click="search"
              plain
              type="primary"
              v-hasPermi="['system:data-standards:search']"
              >搜索</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['system:data-standards:add']"
        >
          新增</el-button
        >
        <el-button
          :loading="exportLoading"
          @click="exportStandard"
          v-hasPermi="['system:data-standards:export']"
        >
          导出</el-button
        >
        <el-button
          :disabled="ids.length == 0"
          type="danger"
          @click="delList"
          v-hasPermi="['system:data-standards:delete']"
        >
          删除
        </el-button>
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <DataStandardsForm ref="standardsFormRef" @success="getList" />
  </div>
</template>

<script setup lang="tsx">
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import { useRouter } from 'vue-router'
import {
  dataStandardsPage,
  dataStandardsDelete,
  dataStandardsClone,
  dataStandardsExport,
  dataStandardsDeleteAll
} from '@/api/dataStandards/standards/index'
import dayjs from 'dayjs'
import DataStandardsForm from './components/dataStandardsForm.vue'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { checkPermi } from '@/utils/permission'
import download from '@/utils/download'
const message = useMessage() // 消息弹窗
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const router = useRouter()
const ids = ref<string[]>([])

/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  dataStandardName: '',
  remark: '',
  status: '',
  type: undefined,
  parentName: undefined,
  createTime: undefined
})

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const tableInfo = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: '标准名称', prop: 'dataStandardName' },
    { label: '备注', prop: 'remark' },
    {
      label: '标准类型',
      render: ({ row }) => {
        return (
          <>
            <div>{row.type == 1 ? '结构化数据' : '非结构化数据'}</div>
          </>
        )
      }
    },
    { label: '父标准名称', prop: 'parentName' },
    {
      label: '状态',
      render: ({ row }) => {
        return (
          <>
            <div>{row.status == '1' ? '开启' : '关闭'}</div>
          </>
        )
      }
    },
    { label: '创建时间', prop: 'createTime' },
    {
      label: '操作项',
      width: '250px',
      render: ({ row }) => {
        return (
          <>
            {checkPermi(['system:data-standards:update']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  openForm('update', row.id)
                }}
              >
                编辑
              </el-button>
            )}

            {checkPermi(['system:data-standards:detail']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  gotoDetail(row)
                }}
              >
                标准详情
              </el-button>
            )}
            {checkPermi(['system:data-standards:clone']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  standardClone(row)
                }}
              >
                克隆
              </el-button>
            )}
            {checkPermi(['system:data-standards:delete']) && (
              <ns-button
                style="margin-left:6px"
                link
                type="danger"
                confirm
                onClick={() => {
                  del(row)
                }}
              >
                删除
              </ns-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const del = (row) => {
  dataStandardsDelete(row.id).then((response) => {
    console.log('response', response)
    tableRef.value.fetchData()
    ElMessage.success('提交成功')
  })
}
const delList = () => {
  proxy?.$modal
    .confirm(`确定要删除所选项吗？`)
    .then(() => {
      dataStandardsDeleteAll(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}
const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await dataStandardsPage({
    page,
    pageSize,
    ...searchValue.value
  })
  return { data, count }
}

/** 添加/修改操作 */
const standardsFormRef = ref()
const openForm = (type: string, id?: number) => {
  standardsFormRef.value.open(type, id)
}

const standardClone = (row) => {
  proxy?.$modal
    .confirm(`确定要克隆该项吗？`)
    .then(() => {
      dataStandardsClone(row.id).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('克隆成功')
      })
    })
    .catch(() => {})
}

const exportLoading = ref(false) // 导出的加载中
const exportStandard = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await dataStandardsExport({
      ...pageParams.value,
      ...searchValue.value,
      ids: ids.value
    })
    download.excel(data, '标准列表.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const getList = () => {
  tableRef.value.fetchData()
}

const gotoDetail = (row) => {
  router.push({
    path: '/system/dataStandardsDetail',
    query: {
      id: row.id,
      type: row.type
    }
  })
}

onMounted(() => {})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
